use crate::REQWEST_CLIENT;
use anyhow::Result;
use log::info;
use log::trace;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

/// [东方财富网 > 行情中心 > 沪深京个股 > 沪深京 A 股](https://quote.eastmoney.com/center/gridlist.html?st=ChangePercent&sortType=C&sortRule=-1#hs_a_board)
///
/// > [好 👌🏻： 可以把 cb=jQuery1124015842536727887713_1707447774042& 删掉, 把 pz=10000 把所有票拿到](https://70.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=10000&po=0&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&wbp2u=|0|0|0|web&fid=f12&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152)
///
/// Mapping to [stock_hu_shen_jing.json](file:///Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/eastmoney/sample/stock_hu_shen_jing.json)
#[derive(Debug, Serialize, Deserialize)]
pub struct StockBoard {
    pub rc: i32,
    pub rt: i32,
    pub svr: u64,
    pub lt: i32,
    pub full: i32,
    pub dlmkts: String,
    pub data: Option<StockBoardData>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StockBoardData {
    pub total: i32,
    pub diff: Vec<StockBoardDataDiff>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StockBoardDataDiff {
    pub f1: Value,
    pub f2: Value,
    pub f3: Value,
    pub f4: Value,
    pub f5: Value,
    pub f6: Value,
    pub f7: Value,
    pub f8: Value,
    pub f9: Value,
    pub f10: Value,
    pub f11: Value,
    pub f12: String,
    pub f13: Value,
    pub f14: String,
    pub f15: Value,
    pub f16: Value,
    pub f17: Value,
    pub f18: Value,
    pub f20: Value,
    pub f21: Value,
    pub f22: Value,
    pub f23: Value,
    pub f24: Value,
    pub f25: Value,
    pub f62: Value,
    pub f115: Value,
    pub f128: Value,
    pub f140: Value,
    pub f141: Value,
    pub f136: Value,
    pub f152: Value,
}

impl StockBoard {
    /// Referer: https://quote.eastmoney.com/center/gridlist.html#hs_a_board
    ///
    /// pn: u16 page-number start from 1,
    ///
    /// pz: u16 page-size e.g. 20
    ///
    pub async fn hs_a_board(pn: u16, pz: u16) -> Result<StockBoard> {
        // GET /api/qt/clist/get?cb=jQuery1124043537917375013624_1708913588242&pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&wbp2u=|0|0|0|web&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1708913588243 HTTP/1.1
        // Accept: */*
        // Accept-Encoding: gzip, deflate, br
        // Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
        // Cache-Control: no-cache
        // Connection: keep-alive
        // Cookie: qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=435; st_psi=20240226101256945-113200301321-5527976132
        // Host: 24.push2.eastmoney.com
        // Pragma: no-cache
        // Referer: https://quote.eastmoney.com/center/gridlist.html#hs_a_board
        // Sec-Fetch-Dest: script
        // Sec-Fetch-Mode: no-cors
        // Sec-Fetch-Site: same-site
        // User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
        // sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"
        // sec-ch-ua-mobile: ?0
        // sec-ch-ua-platform: "macOS"

        let host = "push2his.eastmoney.com";
        // Query String Parameters:
        //cb: jQuery112404647052438469883_1711520292103
        // let pn= 1;
        // let pz= 20;
        let po = 0;
        let np = 1;
        let ut = utils::generate_random_hex_string(32); //"bd1d9ddb04089700cf9c27f6f7426281";
        let fltt = 2;
        let invt = 2;
        let wbp2u = "|0|0|0|web";
        let fid = "f12";
        let fs = "m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048";
        let fields =
            "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152";
        let t_ = utils::duration_ms_since_epoch(); //1711520292104;

        let request_url = format!(
            "https://{host}/api/qt/clist/get?pn={pn}&pz={pz}&po={po}&np={np}&ut={ut}&fltt={fltt}&invt={invt}&wbp2u={wbp2u}&fid={fid}&fs={fs}&fields={fields}&_={t_}"
        );
        info!("\n (hs_a_board) request_url= {}\n", request_url);

        let response = REQWEST_CLIENT.get(request_url)
            .header(reqwest::header::ACCEPT, "*/*")
            .header(reqwest::header::ACCEPT_ENCODING, "gzip, deflate, br")
            .header(reqwest::header::ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8")
            .header(reqwest::header::CACHE_CONTROL, "no-cache")
            .header(reqwest::header::CONNECTION, "keep-alive")
            // .header(reqwest::header::COOKIE, "qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=438; st_psi=20240226102321941-113200301321-9024721593")
            .header(reqwest::header::HOST, format!("{host}"))
            .header(reqwest::header::PRAGMA, "no-cache")
            .header(
                reqwest::header::REFERER,
                "https://quote.eastmoney.com/center/gridlist.html#hs_a_board"
            )
            .header(
                reqwest::header::USER_AGENT,
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
            )
            .header(
                "Sec-Ch-Ua",
                "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
            )
            .header("Sec-Ch-Ua-Mobile", "?0")
            .header("Sec-Ch-Ua-Platform", "\"macOS\"")
            .header("Sec-Fetch-Dest", "empty")
            .header("Sec-Fetch-Mode", "cors")
            .header("Sec-Fetch-Site", "same-origin")
            .send().await?;

        let body = response.text().await?;

        // println!("*** (hs_a_board) body={}\n\nhangqin\n\n", body);

        let fund: StockBoard = serde_json::from_str(&body)?;

        // println!("{:?}", fund);

        Ok(fund)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn test_hs_a_board() {
        let stock_board = StockBoard::hs_a_board(1, 10).await.unwrap();

        if let StockBoard { data: Some(StockBoardData { diff, .. }), .. } = stock_board {
            for (idx, df) in diff.iter().enumerate() {
                println!("[{:00004}] {},{} ", idx, df.f12, df.f14);
            }
        }
    }
}
